package com.ruoyi.qbms.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;

import com.ruoyi.common.constant.QbmsConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.qbms.domain.*;
import com.ruoyi.qbms.domain.dto.QbmsQuestionChoiceImportDto;
import com.ruoyi.qbms.service.IQbmsCategoryService;
import com.ruoyi.qbms.service.IQbmsChapterService;
import com.ruoyi.qbms.service.IQbmsSubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.qbms.mapper.QbmsQuestionChoiceMapper;
import com.ruoyi.qbms.service.IQbmsQuestionChoiceService;

/**
 * 题库选择题Service业务层处理
 * 
 * @author zouhuu
 * @date 2022-10-17
 */
@Service
public class QbmsQuestionChoiceServiceImpl implements IQbmsQuestionChoiceService 
{
    @Autowired
    private QbmsQuestionChoiceMapper qbmsQuestionChoiceMapper;

    @Autowired
    private IQbmsCategoryService qbmsCategoryService;

    @Autowired
    private IQbmsSubjectService qbmsSubjectService;

    @Autowired
    private IQbmsChapterService qbmsChapterService;

    /**
     * 查询题目数量
     * @param qbmsQuestionChoice
     * @return
     */
    @Override
    public int selectNums(QbmsQuestionChoice qbmsQuestionChoice) {
        return qbmsQuestionChoiceMapper.selectNums(qbmsQuestionChoice);
    }

    /**
     * 客户端查询题目章节数据
     * @param qbmsQuestionChoice
     * @return
     */
    @Override
    public List<QbmsQuestionChoice> clientSelectQuestionChapterData(QbmsQuestionChoice qbmsQuestionChoice) {
        return qbmsQuestionChoiceMapper.clientSelectQuestionChapterData(qbmsQuestionChoice);
    }
    /**
     * 客户端查询题目数据
     * @param qbmsQuestionChoice
     * @return
     */
    @Override
    public List<QbmsQuestionChoice> clientSelectQbmsQuestionList(QbmsQuestionChoice qbmsQuestionChoice) {
        return qbmsQuestionChoiceMapper.clientSelectQbmsQuestionList(qbmsQuestionChoice);
    }

    /**
     * 查询题库选择题
     * 
     * @param id 题库选择题主键
     * @return 题库选择题
     */
    @Override
    public QbmsQuestionChoice selectQbmsQuestionChoiceById(Long id)
    {
        return qbmsQuestionChoiceMapper.selectQbmsQuestionChoiceById(id);
    }

    /**
     * 查询简单题目信息
     * @param id
     * @return
     */
    @Override
    public QbmsQuestionChoice selectSimpleQuestionById(Long id) {
        return qbmsQuestionChoiceMapper.selectSimpleQuestionById(id);
    }

    /**
     * 查询题库选择题列表
     * 
     * @param qbmsQuestionChoice 题库选择题
     * @return 题库选择题
     */
    @Override
    public List<QbmsQuestionChoice> selectQbmsQuestionChoiceList(QbmsQuestionChoice qbmsQuestionChoice)
    {
        return qbmsQuestionChoiceMapper.selectQbmsQuestionChoiceList(qbmsQuestionChoice);
    }

    /**
     * 查询题目列表根据id集合
     * @param ids
     * @return
     */
    @Override
    public List<QbmsQuestionChoice> selectQbmsQuestionByIds(Collection<Long> ids) {
        return qbmsQuestionChoiceMapper.selectQbmsQuestionByIds(ids);
    }

    /**
     * 新增题库选择题
     * 
     * @param qbmsQuestionChoice 题库选择题
     * @return 结果
     */
    @Transactional
    @Override
    public int insertQbmsQuestionChoice(QbmsQuestionChoice qbmsQuestionChoice)
    {
        qbmsQuestionChoice.setCreateTime(DateUtils.getNowDate());
        qbmsQuestionChoice.setCreateBy(SecurityUtils.getUsername());
        qbmsQuestionChoice.setUserId(SecurityUtils.getUserId());
        qbmsQuestionChoice.setDeptId(SecurityUtils.getUserId());
        int rows = qbmsQuestionChoiceMapper.insertQbmsQuestionChoice(qbmsQuestionChoice);
        insertQbmsQuestionChoiceIssue(qbmsQuestionChoice);
        return rows;
    }

    /**
     * 修改题库选择题
     * 
     * @param qbmsQuestionChoice 题库选择题
     * @return 结果
     */
    @Transactional
    @Override
    public int updateQbmsQuestionChoice(QbmsQuestionChoice qbmsQuestionChoice) {
        qbmsQuestionChoice.setUpdateTime(DateUtils.getNowDate());
        qbmsQuestionChoice.setUpdateBy(SecurityUtils.getUsername());
        qbmsQuestionChoiceMapper.deleteQbmsQuestionChoiceIssueByQuestionId(qbmsQuestionChoice.getId());
        insertQbmsQuestionChoiceIssue(qbmsQuestionChoice);
        return qbmsQuestionChoiceMapper.updateQbmsQuestionChoice(qbmsQuestionChoice);
    }

    /**
     * 批量删除题库选择题
     * 
     * @param ids 需要删除的题库选择题主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteQbmsQuestionChoiceByIds(Long[] ids)
    {
        qbmsQuestionChoiceMapper.deleteQbmsQuestionChoiceIssueByQuestionIds(ids);
        return qbmsQuestionChoiceMapper.deleteQbmsQuestionChoiceByIds(ids);
    }

    /**
     * 删除题库选择题信息
     * 
     * @param id 题库选择题主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteQbmsQuestionChoiceById(Long id)
    {
        qbmsQuestionChoiceMapper.deleteQbmsQuestionChoiceIssueByQuestionId(id);
        return qbmsQuestionChoiceMapper.deleteQbmsQuestionChoiceById(id);
    }

    /**
     * 导入题库信息
     * @param questionImportList
     * @param categoryId
     * @return
     */
    @Transactional
    @Override
    public String importQuestionChoice(List<QbmsQuestionChoiceImportDto> questionImportList, Long categoryId) {
        // 按 学科 和 章节分组
        Map<String, Map<String, List<QbmsQuestionChoiceImportDto>>> subjectChapterMap = questionImportList.stream()
                .collect(Collectors.groupingBy(QbmsQuestionChoiceImportDto::getSubjectName,
                        Collectors.groupingBy(QbmsQuestionChoiceImportDto::getChapterName)));

        // 查询分类信息
        QbmsCategory category = qbmsCategoryService.selectQbmsCategoryById(categoryId);

        // 查询所有学科
        QbmsSubject qbmsSubjectParams = new QbmsSubject();
        qbmsSubjectParams.setCategoryId(categoryId);
        Map<String, QbmsSubject> subjectMap = qbmsSubjectService.selectQbmsSubjectOptions(qbmsSubjectParams)
                .stream().collect(Collectors.toMap(QbmsSubject::getName, QbmsSubject -> QbmsSubject));

        // 查询所有章节
        QbmsChapter qbmsChapterParams = new QbmsChapter();
        qbmsChapterParams.setCategoryId(categoryId);
        Map<String, QbmsChapter> chapterMap = qbmsChapterService.selectQbmsChapterOptions(qbmsChapterParams)
                .stream().collect(Collectors.toMap(p -> p.getSubjectName() + "-" + p.getName(), QbmsChapter -> QbmsChapter));

        // 遍历分组
        subjectChapterMap.forEach((subjectName, chapterQuestionMap) -> {
            // 获取学科信息
            QbmsSubject subjectInfo = getSubjectInfo(subjectMap, category, subjectName);
            chapterQuestionMap.forEach((chapterName, questionList) -> {
                // 获取章节信息
                QbmsChapter chapterInfo = getChapterInfo(chapterMap, subjectInfo, chapterName);

                // 批量添加题目
                List<QbmsQuestionChoice> qbmsQuestionChoices = buildImportQuestionList(questionList, chapterInfo);

                for (QbmsQuestionChoice question : qbmsQuestionChoices ) { // 插入题目
                    insertQbmsQuestionChoice(question);
                }
            });

        });
        return "导入成功";
    }

    /**
     * 新增题库选择题问题信息
     * 
     * @param qbmsQuestionChoice 题库选择题对象
     */
    public void insertQbmsQuestionChoiceIssue(QbmsQuestionChoice qbmsQuestionChoice)
    {
        List<QbmsQuestionChoiceIssue> qbmsQuestionChoiceIssueList = qbmsQuestionChoice.getQbmsQuestionChoiceIssueList();
        Long id = qbmsQuestionChoice.getId();
        if (StringUtils.isNotNull(qbmsQuestionChoiceIssueList))
        {
            List<QbmsQuestionChoiceIssue> list = new ArrayList<QbmsQuestionChoiceIssue>();
            for (QbmsQuestionChoiceIssue qbmsQuestionChoiceIssue : qbmsQuestionChoiceIssueList)
            {
                qbmsQuestionChoiceIssue.setQuestionId(id);
                list.add(qbmsQuestionChoiceIssue);
            }
            if (list.size() > 0)
            {
                qbmsQuestionChoiceMapper.batchQbmsQuestionChoiceIssue(list);
            }
        }
    }



    /** 拼接选项 */
    public String contactOptions(QbmsQuestionChoiceImportDto question) {
        String options = question.getOptionsA() + "====" + question.getOptionsB();
        if (StringUtils.isNotEmpty(question.getOptionsC())) {
            options = options + "====" + question.getOptionsC();
        }
        if (StringUtils.isNotEmpty(question.getOptionsD())) {
            options  = options + "====" + question.getOptionsD();
        }
        if (StringUtils.isNotEmpty(question.getOptionsE())) {
            options  = options + "====" + question.getOptionsE();
        }
        if (StringUtils.isNotEmpty(question.getOptionsF())) {
            options  = options + "====" + question.getOptionsF();
        }
        return options;
    }

    /** 转换答案 */
    public String convertAnswerToNumStr(String answerStr) {
        char[] charArr = answerStr.toCharArray();
        String str = "";
        for(int i = 0; i < charArr.length; i++){
            char ch = charArr[i];
            int num = ch - 64;
            if (i != charArr.length -1) {
                str += num + ",";
            } else {
                str += num;
            }
        }
        return str;
    }

    /**
     * 获取科目信息
     * @param subjectMap
     * @param category
     * @param subjectName
     * @return
     */
    public QbmsSubject getSubjectInfo(Map<String, QbmsSubject> subjectMap, QbmsCategory category, String subjectName) {
        QbmsSubject subject = subjectMap.get(subjectName);
        if (StringUtils.isNull(subject)) { // 不存在即添加新学科
            subject = new QbmsSubject();
            subject.setName(subjectName);
            subject.setCategoryId(category.getId());
            subject.setCategoryName(category.getName());
            qbmsSubjectService.insertQbmsSubject(subject);
        }
        return subject;
    }

    /**
     * 获取章节信息
     * @param chapterMap
     * @param subjectInfo
     * @param chapterName
     * @return
     */
    public QbmsChapter getChapterInfo(Map<String, QbmsChapter> chapterMap, QbmsSubject subjectInfo, String chapterName) {
        QbmsChapter qbmsChapter = chapterMap.get(subjectInfo.getName() + "-" + chapterName);
        if (StringUtils.isNull(qbmsChapter)) { // 不存在添加新章节
            qbmsChapter = new QbmsChapter();
            qbmsChapter.setName(chapterName);
            qbmsChapter.setSubjectId(subjectInfo.getId());
            qbmsChapter.setSubjectName(subjectInfo.getName());
            qbmsChapter.setCategoryId(subjectInfo.getCategoryId());
            qbmsChapter.setCategoryName(subjectInfo.getCategoryName());
            qbmsChapterService.insertQbmsChapter(qbmsChapter);
        }
        return qbmsChapter;
    }

    /**
     * 构建题目导入列表
     * @param questionImportList
     * @param chapter
     */
    public List<QbmsQuestionChoice> buildImportQuestionList(List<QbmsQuestionChoiceImportDto> questionImportList, QbmsChapter chapter) {
        List<QbmsQuestionChoice> questionList = new ArrayList<>();
        for (int i = 0; i < questionImportList.size(); i++) {
            QbmsQuestionChoiceImportDto questionDto = questionImportList.get(i);

            QbmsQuestionChoice qbmsQuestionChoice = new QbmsQuestionChoice();
            // 设置基本信息
            qbmsQuestionChoice.setCategoryId(chapter.getCategoryId());
            qbmsQuestionChoice.setCategoryName(chapter.getCategoryName());
            qbmsQuestionChoice.setSubjectId(chapter.getSubjectId());
            qbmsQuestionChoice.setSubjectName(chapter.getSubjectName());
            qbmsQuestionChoice.setChapterId(chapter.getId());
            qbmsQuestionChoice.setChapterName(chapter.getName());

            qbmsQuestionChoice.setStem(questionDto.getStem());
            qbmsQuestionChoice.setChoiceCategory(questionDto.getChoiceCategory());
            qbmsQuestionChoice.setChoiceType(questionDto.getChoiceType());

            // 构建问题信息
            ArrayList<QbmsQuestionChoiceIssue> issueList = new ArrayList<>();
            QbmsQuestionChoiceIssue qbmsQuestionChoiceIssue = new QbmsQuestionChoiceIssue();
            qbmsQuestionChoiceIssue.setIssue(questionDto.getIssue()); // 问题
            qbmsQuestionChoiceIssue.setAnswer(convertAnswerToNumStr(questionDto.getAnswer())); // 答案
            qbmsQuestionChoiceIssue.setAnswerExplain(questionDto.getAnswerExplain()); // 答案解释
            qbmsQuestionChoiceIssue.setIssueOptions(contactOptions(questionDto)); // 选项
            issueList.add(qbmsQuestionChoiceIssue);
            // 选择题类型
            Integer choiceCategory = questionDto.getChoiceCategory();
            // 判断是否是主子题
            if (QbmsConstants.QBMS_CHOICE_CATEGORY_SINGLE_ANSWER_STEM.equals(choiceCategory) || QbmsConstants.QBMS_CHOICE_CATEGORY_SINGLE_ANSWER_OPTIONS.equals(choiceCategory) || QbmsConstants.QBMS_CHOICE_CATEGORY_MULTIPLE_ANSWER_STEM.equals(choiceCategory)) {
                while (true) {
                    int nexti = i + 1;
                    if (nexti >= questionImportList.size()) { // 判断是否能够退出循环
                        break;
                    }
                    QbmsQuestionChoiceImportDto nextImportDto = questionImportList.get(nexti);

                    QbmsQuestionChoiceIssue nextIssue = new QbmsQuestionChoiceIssue(); // 下一题
                    nextIssue.setIssue(nextImportDto.getIssue()); // 问题
                    nextIssue.setAnswer(convertAnswerToNumStr(nextImportDto.getAnswer())); // 答案
                    nextIssue.setAnswerExplain(nextImportDto.getAnswerExplain()); // 答案解释
                    nextIssue.setIssueOptions(contactOptions(nextImportDto)); // 选项

                    if (QbmsConstants.QBMS_CHOICE_CATEGORY_SINGLE_ANSWER_OPTIONS.equals(choiceCategory)) {  // 共用答案单选题
                        if (qbmsQuestionChoiceIssue.getIssueOptions().equals(nextIssue.getIssueOptions())) { // 如果下一题选项相同着添加
                            issueList.add(nextIssue);
                            i = nexti;
                        } else {
                            break;
                        }
                    } else { // 共用题干单选题  共用题干多选题

                        if (questionDto.getStem().equals(nextImportDto.getStem())) {
                            issueList.add(nextIssue);
                            i = nexti;
                        } else {
                            break;
                        }
                    }
                }
            }
            qbmsQuestionChoice.setQbmsQuestionChoiceIssueList(issueList);
            questionList.add(qbmsQuestionChoice);
        }
        return questionList;
    }



}
